//
//  CRStatusController.swift
//  GZWeibo007
//
//  Created by jiwang on 15/12/24.
//  Copyright © 2015年 Apple. All rights reserved.
//

import UIKit

class CRStatusController: UIViewController , UITableViewDataSource , UITableViewDelegate , CZStatusForwardCellDeleagte,CZStatusBottomViewDelegate {
    
    var statuses : CZStatus? {
        didSet {
            //控制器刷新
            tableView.reloadData()
        }
    }
    
    //评论数组
    private var comment : [CZStatus]? {
        didSet {
            self.tableView.reloadData()
        }
    }
    
    override func viewDidLoad() {
        
        super.viewDidLoad()
        bottomView.delegate = self
        prepareUI()
        
        //注册通知中心
        let center = NSNotificationCenter.defaultCenter()
        center.addObserver(self, selector: "removedSelf", name: "remove", object: nil)
        center.addObserver(self, selector: "reflash", name: "commend", object: nil)
    }
    
    func prepareUI() {
        view.addSubview(bottomView)
        view.addSubview(tableView)
        headView.addSubview(NoCommendLabel)
        
        tableView.delegate = self
        tableView.dataSource = self
        tableView.sectionHeaderHeight = 40
        
        bottomView.ff_AlignInner(type: ff_AlignType.BottomLeft, referView: view, size: CGSize(width: UIScreen.mainScreen().bounds.width, height: 44))
        tableView.ff_AlignInner(type: ff_AlignType.TopLeft, referView: view, size: nil, offset: CGPoint(x: 0, y: 40))
        tableView.ff_AlignVertical(type: ff_AlignType.TopRight, referView: bottomView, size: nil)
        
        NoCommendLabel.ff_AlignVertical(type: ff_AlignType.BottomCenter, referView: headView, size: nil, offset: CGPoint(x: 0, y: 10))
        
        //注册cell
        tableView.registerClass(CZStatusForwardCell.self, forCellReuseIdentifier: CZStatusCellReuseIdentifier.StatusForwardCell.rawValue)
        tableView.registerClass(CZStatusNormalCell.self, forCellReuseIdentifier: CZStatusCellReuseIdentifier.StatusNormalCell.rawValue)
        tableView.registerClass(CRCommendCell.self, forCellReuseIdentifier: CZStatusCellReuseIdentifier.StatusCommendCell.rawValue)
        
        tableView.addInfiniteScrollingWithActionHandler { () -> Void in
            
            self.loadMoreCommend()
        }
        
        // 先不显示上拉加载更多的菊花
        tableView.showsInfiniteScrolling = false
    }
    
    func loadMoreCommend () {
        let max_id = comment?.last?.id ?? 0
        
        CZNetworkTool.sharedInstance.loadComments(statuses!, max_id: max_id) { (result, error) -> () in
            self.tableView.infiniteScrollingView.stopAnimating()
            
            if error != nil {
                print("上啦刷新出错")
                return
            }
            
            let count = result?.count ?? 0
            if count == 0 {
                print("没有加载到数据")
                return
            }
            
            if max_id > 0 {
                // 最终的数据 = 现有数据 + 获取到的数据
                self.comment = self.comment! + result!
                print("上拉加载到更多数据: \(count)条")
            }
        }
    }
    
    // MARK: - Table view 数据源方法
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 2
    }
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        if section == 0 {
            return 1
        }
        
        return comment?.count ?? 0
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        let UsedId = statuses?.cellID()
        
        if indexPath.section == 0 {
            let cell = tableView.dequeueReusableCellWithIdentifier(UsedId!) as! CZStatusCell
            cell.status = statuses
            cell.bottomView.updateButtonCount(statuses!)
            cell.cellDelegate = self
            return cell
        }else {
            let cell = tableView.dequeueReusableCellWithIdentifier(CZStatusCellReuseIdentifier.StatusCommendCell.rawValue) as! CRCommendCell
            cell.status = comment![indexPath.row]
            return cell
        }
    }
    
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        if indexPath.section == 0 {
            
            if statuses?.rowHeight != nil {
                return (statuses?.rowHeight)!
            }
            let UsedId = statuses?.cellID()
            
            let cell = tableView.dequeueReusableCellWithIdentifier(UsedId!) as! CZStatusCell
            
            return cell.rowHeight(statuses!)
            
        }else {
            
            let cell = tableView.dequeueReusableCellWithIdentifier(CZStatusCellReuseIdentifier.StatusCommendCell.rawValue) as! CRCommendCell
            return cell.rowHeight(comment![indexPath.row])
        }
    }
    
    func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return headView
    }
    
    //MARK: - cell 的代理方法
    func changeToNormalController(status: CZStatus) {
        let vc = CRStatusController()
        vc.statuses = statuses?.retweeted_status
        vc.title = "微博详情"
        vc.hidesBottomBarWhenPushed = true
        navigationController?.pushViewController(vc, animated: true)
    }
    //MARK: 按钮代理方法
    //转发
    func repostButtonClick()
    {
        let repostVC = CRComposeViewController(controllerType: CRComposeViewControllertype.repost)
        repostVC.status = statuses
        presentViewController(UINavigationController(rootViewController: repostVC), animated: true, completion: nil)
    }
    //评论
    func commentButtonClick()
    {
        
        let commentVC = CRComposeViewController(controllerType: CRComposeViewControllertype.comment)
        commentVC.status = statuses
        presentViewController(UINavigationController(rootViewController: commentVC), animated: true, completion: nil)
    }

    
    func commendDidClick () {
        CZNetworkTool.sharedInstance.loadComments(statuses!, max_id: 0) { (result, error) -> () in
            if error != nil {
                print("加载出错")
                return
            }
            
            if result!.count == 0 {
                print("暂时没有评论")
                self.NoCommendLabel.alpha = 1
                return
            }
            
            //来到这里表示有数据
            self.tableView.showsInfiniteScrolling = true
            self.NoCommendLabel.alpha = 0
            self.comment = result
        }
    }
    
    //MARK: - 通知方法
    func removedSelf() {
        self.navigationController?.popToRootViewControllerAnimated(false)
        self.view.removeFromSuperview()
    }
    
    func reflash () {
        self.commendDidClick()
    }
    
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
        print("详情死了")
    }
    
    //MARK: - 懒加载
    private lazy var bottomView : CZStatusBottomView = CZStatusBottomView()
    private lazy var tableView : UITableView = UITableView(frame: CGRectMake(0, 0, 0, 0), style: UITableViewStyle.Grouped)
    private lazy var headView : UIView = {
        
        let view = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.mainScreen().bounds.width, height: 40))
        view.backgroundColor = UIColor.whiteColor()
        
        let button = UIButton(imageName: "timeline_icon_comment", fontSize: 11, title: "评论")
        button.frame = CGRect(x: 5, y: 5, width: 50, height: 30)
        button.backgroundColor = UIColor.whiteColor()
        button.addTarget(self, action: "commendDidClick", forControlEvents: UIControlEvents.TouchUpInside)
        view.addSubview(button)
        
        return view
    }()
    
    private lazy var NoCommendLabel : UILabel = {
       let label = UILabel()
        label.text = "暂时没有评论"
        label.textColor = UIColor(white: 0.66, alpha: 1)
        label.sizeToFit()
        label.font = UIFont.systemFontOfSize(14)
        label.alpha = 0
        return label
    }()
}